package com.neu.cloudFactory.service;

import com.neu.cloudFactory.DAO.EquipMsgDAO;
import com.neu.cloudFactory.DAO.EquipTypeDAO;
import com.neu.cloudFactory.DAO.FactoryDAO;
import com.neu.cloudFactory.DAO.UserDAO;
import com.neu.cloudFactory.PO.EquipMsg;
import com.neu.cloudFactory.PO.Factory;
import com.neu.cloudFactory.VO.EquipMsgVO;
import com.neu.cloudFactory.VO.RentVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class RentService {
    final UserDAO userDAO;
    final EquipMsgDAO equipMsgDAO;
    final EquipTypeDAO equipTypeDAO;
    final FactoryDAO factoryDAO;

    public RentService(UserDAO userDAO, EquipMsgDAO equipMsgDAO, EquipTypeDAO equipTypeDAO, FactoryDAO factoryDAO) {
        this.userDAO = userDAO;
        this.equipMsgDAO = equipMsgDAO;
        this.equipTypeDAO = equipTypeDAO;
        this.factoryDAO = factoryDAO;
    }

    //     列出所有可租用设备
    public List<RentVO> findAllRentable() {
        List<EquipMsg> equipMsgList = equipMsgDAO.findByRentState("未被租用", "产能中心");
        List<RentVO> rentVOList = new ArrayList<>();
        //转换为RentVO
        for (EquipMsg equipMsg : equipMsgList) {
            rentVOList.add(new RentVO(
                    equipMsg, equipTypeDAO.getById(equipMsg.getTypeId()),
                    userDAO.findByName("admin"))
            );
        }
        System.out.println(rentVOList);
        return rentVOList;
    }

    //    租用设备
    public EquipMsgVO rentEquip(RentVO rentVO) {
        EquipMsg equipMsg = equipMsgDAO.getById(Integer.parseInt(rentVO.getId()));
        //被租用设备的设备信息
        equipMsgDAO.modifyRentState("已被租用", equipMsg.getId());
        //修改设备所属工厂
        equipMsgDAO.modifyFactory(factoryDAO.findByUserId(userDAO.findByAccount(rentVO.getFactoryAccount()).getId()).getId(), equipMsg.getId());
        // 修改到设备table
        EquipMsg oriEquip = equipMsgDAO.getById(equipMsg.getId());
        equipMsgDAO.save(oriEquip);
        return new EquipMsgVO(oriEquip,
                factoryDAO.findByUserId(userDAO.findByAccount(rentVO.getFactoryAccount()).getId()),
                equipTypeDAO.getById(oriEquip.getTypeId()),
                rentVO.getFactoryAccount());
    }
}
